package com.china_goldcard.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该 PagerAdapter 的实现将只保留当前页面，
 * 当页面离开视线后，就会被消除，释放其资源；
 * 而在页面需要显示时，生成新的页面(就像 ListView 的实现一样)。
 * 这么实现的好处就是当拥有大量的页面时，
 * 不必在内存中占用大量的内存
 */
public class BaseFragmentStatePageAdapter<T extends Fragment> extends FragmentStatePagerAdapter {

    protected List<T> dataList;

    protected Map<String,T> fragmentMaps = new HashMap<String,T>();

    public BaseFragmentStatePageAdapter(FragmentManager fm, List<T> dataList) {
        super(fm);
        this.dataList = dataList;
    }

    @Override
    public Fragment getItem(int position) {
        T fragment = fragmentMaps.get(fragmentMapKey(position));
        if (fragment == null){
            fragment = dataList.get (position);
            fragmentMaps.put (fragmentMapKey(position), fragment);
        }
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container,position,object);
        fragmentMaps.remove (fragmentMapKey(position));
    }

    /**
     * index生成key
     * @param index
     * @return
     */
    private String fragmentMapKey(int index){
        return "FragmentMapKey" + index;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }
}
